import jieba
import joblib
import pandas as pd
from keras.models import load_model
from keras.preprocessing.sequence import pad_sequences

label_encoder = joblib.load('label_encoder.pkl')

# 1. 确保定义了中文分词器
def chinese_tokenizer(text):
    return list(jieba.cut(text))

# 2. 使用模型进行预测
def predict_with_models(new_texts):
    # 加载保存的模型和向量化器
    vectorizer = joblib.load('tfidf_vectorizer.pkl')
    # label_encoder = joblib.load('label_encoder.pkl')
    lr_model = joblib.load('lr_model.pkl')
    lstm_model = load_model('lstm_model.h5')
    
    # 处理输入文本
    new_texts_vectorized = vectorizer.transform(new_texts).toarray()  # 使用训练时的vectorizer进行转换
    new_texts_padded = pad_sequences(new_texts_vectorized, padding='post', maxlen=100)
    
    # 使用LSTM模型进行预测
    lstm_predictions = lstm_model.predict(new_texts_padded)
    lstm_predictions = (lstm_predictions > 0.5).astype(int)  # 将输出转为0或1
    
    # 打印LSTM预测结果
    print("\nLSTM Model - Prediction Results:")
    for text, pred in zip(new_texts, lstm_predictions):
        print(f"文本: {text} => 预测标签: {label_encoder.inverse_transform([pred])[0]}")
    
    # 使用Logistic Regression进行预测
    lr_predictions = lr_model.predict(new_texts_vectorized)
    print("\nLogistic Regression - Prediction Results:")
    for text, pred in zip(new_texts, lr_predictions):
        print(f"文本: {text} => 预测标签: {label_encoder.inverse_transform([pred])[0]}")
    return lr_predictions
# 测试模型的预测功能

# 1. 数据准备 - 从Excel文件加载数据
new_texts = ["航向改为270", "高度保持3000英尺", "已经降落至1000英尺"]
predict_result = predict_with_models(new_texts)